<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :inline="true" size="small" :model="queryParams" class="demo-form-inline"
             v-hasPermi="['res:copyright:query']">
      <el-form-item label="名称" prop="name">
        <el-input v-model.trim="queryParams.name" clearable :maxlength="50" placeholder="请输入名称"/>
      </el-form-item>
      <el-form-item label="著作权人" prop="rightHolder">
        <el-input v-model="queryParams.rightHolder" :maxlength="50" clearable
                  placeholder="请输入著作权人"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="请选择状态"
                   default-first-option filterable style="width: 100%;">
          <el-option v-for="item in dict.type.sys_copyright_status" :key="item.value" :label="item.label"
                     :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="取得方式" prop="acquisitionMethod">
        <el-select v-model="queryParams.acquisitionMethod" clearable placeholder="请选择取得方式" default-first-option
                   filterable
                   style="width: 100%;">
          <el-option v-for="item in dict.type.sys_obtain_method" :key="item.value" :label="item.label"
                     :value="+item.value"/>
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="发明人" prop="inventor">-->
      <!--        <el-input v-model="queryParams.inventor" :maxlength="50" clearable placeholder="请选择发明人"></el-input>-->
      <!--      </el-form-item>-->
      <el-form-item label="对应设备" prop="correspondingDevice">
        <el-input v-model="queryParams.correspondingDevice" :maxlength="50" clearable
                  placeholder="请输入对应设备"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetHandler">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="24">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['res:copyright:add']"
                     @click="openDialog(null)">增加
          </el-button>
          <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['res:copyright:export']"
                     @click="exportHandler">导出
          </el-button>
          <span class=" text" style="margin-left: 10px;">已登记的软著: {{ copyrightCount ? copyrightCount : 0 }}</span>
        </div>
      </el-col>
    </el-row>

    <el-table
      ref="tableRef"
      :data="tableData"
      highlight-current-row
      max-height="680"
      v-loading="loading"
      v-horizontal-scroll="'auto'"
      style="width: 100%;margin-top: 10px;">
      <el-table-column
        property="registrationNumber"
        label="登记号"
        align="center"
      />
      <el-table-column
        property="name"
        label="名称"
        align="center"
      />
      <el-table-column
        property="acquisitionMethod"
        label="取得方式"
        align="center"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_obtain_method" :value="scope.row.acquisitionMethod"/>
        </template>
      </el-table-column>
      <el-table-column
        property="rightHolder"
        label="著作权人"
        align="center"
      />
      <el-table-column
        property="transferorUnit"
        label="转让前单位"
        align="center"
        min-width="100"
      />
      <el-table-column
        property="transferorDate"
        label="转让日期"
        align="center"
      />
      <el-table-column
        property="applicationDate"
        label="申请日期"
        align="center"
      />
      <el-table-column
        property="status"
        label="状态"
        align="center"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_copyright_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column
        property="authorizationDate"
        label="下证日期"
        align="center"
      />
      <el-table-column
        property="series"
        label="所属系列"
        align="center"
      />
      <el-table-column
        property="correspondingDevice"
        label="对应设备"
        align="center"
      />
      <el-table-column
        property="highNewUsage"
        label="高新使用情况"
        align="center"
        min-width="120"
      />
      <el-table-column
        property="remark"
        label="备注"
        align="center"
      />
      <el-table-column
        property="createBy"
        label="创建人"
        align="center"
      />
      <el-table-column
        property="createTime"
        label="创建时间"
        align="center"
        min-width="140"
        sortable
      />
      <el-table-column
        label="操作"
        align="center"
        v-if="$auth.hasPermi('res:copyright:edit') || $auth.hasPermi('res:copyright:remove') || $auth.hasPermi('res:copyright:view')"
      >
        <template slot-scope="scope">
          <el-button v-if="scope.row.certificate && $auth.hasPermi('res:copyright:view')" type="text"
                     icon="el-icon-document" @click="handleView2(scope.row)">
            查看软著
          </el-button>
          <el-button type="text" icon="el-icon-view" v-hasPermi="['res:copyright:view']" @click="handleView(scope.row)">
            详情
          </el-button>
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['res:copyright:edit']" @click="openDialog(scope.row)">
            修改
          </el-button>
          <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            title="确定删除吗？"
            @confirm="deleteHandler(scope.row)"
          >
            <el-button slot="reference" icon="el-icon-delete" v-hasPermi="['res:copyright:remove']" type="text"
                       style="margin-left: 10px">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialogTitle === 1 ? '新增' : '修改'"
      :visible.sync="dialogVisible"
      width="700px"
      :close-on-click-modal="false"
      :fullscreen="device === 'mobile'"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="demo-form"
               :label-position="device === 'mobile' ? 'top' : 'right'">
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="登记号" prop="registrationNumber">
              <el-input v-model.trim="form.registrationNumber" clearable :maxlength="50" placeholder="请输入登记号"/>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="名称" prop="name">
              <el-input v-model.trim="form.name" clearable :maxlength="50" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="取得方式" prop="acquisitionMethod">
              <el-select v-model="form.acquisitionMethod" clearable placeholder="请选择取得方式" default-first-option
                         filterable
                         style="width: 100%;">
                <el-option v-for="item in dict.type.sys_obtain_method" :key="item.value" :label="item.label"
                           :value="+item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="著作权人" prop="rightHolder">
              <el-select v-model="form.rightHolder" clearable placeholder="请选择著作权人" multiple allow-create
                         default-first-option filterable style="width: 100%;">
                <!--                <el-option v-for="item in []" :key="item.value" :label="item.label" :value="item.value"/>-->
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="转让前单位" prop="transferorUnit">
              <el-input v-model.trim="form.transferorUnit" :maxlength="20" placeholder="请输入转让前单位"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="申请日期">
              <el-date-picker
                v-model="form.applicationDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="转让日期" prop="transferorDate">
              <el-date-picker
                v-model="form.transferorDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" clearable placeholder="请选择状态"
                         default-first-option filterable style="width: 100%;">
                <el-option v-for="item in dict.type.sys_copyright_status" :key="item.value" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="下证日期" prop="authorizationDate">
              <el-date-picker
                v-model="form.authorizationDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择下证日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="所属系列">
              <el-select v-model="form.series" size="small" clearable filterable placeholder="请选择所属系列" multiple>
                <el-option
                  v-for="item in dict.type.sys_product_series"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="对应设备">
              <el-select v-model="form.correspondingDevice" clearable placeholder="请选择对应设备" multiple
                         default-first-option filterable style="width: 100%;">
                <el-option v-for="item in productList" :key="item.id" :label="item.productName"
                           :value="item.productName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="device === 'mobile' ? 24 : 12">
            <el-form-item label="使用情况" prop="highNewUsage">
              <el-input v-model.trim="form.highNewUsage" :maxlength="100" placeholder="请输入高新使用情况"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="软著证书">
<!--          <div slot="label" class=" red-dot">软著证书</div>-->
          <el-upload class="upload-demo" ref="upload" action="#" :limit="1" :on-change="handleChange"
                     :on-remove="handleRemove" :file-list="fileList" :auto-upload="false" accept=".pdf">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" :maxlength="200"
                    placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="uploadLoading" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi} from "@/api/saas/research/property/copyright";
import {getUserProfile} from "@/api/system/user";
import {mapGetters} from 'vuex'
import {uploadImgApi} from "@/api/after/serve";
import {isFileOfType} from "@/utils";
import {getDataListApi as getAllProductApi} from "@/api/crm/md/product";

export default {
  name: 'ResearchCopyright',
  dicts: ['sys_obtain_method', 'sys_copyright_status', 'sys_product_series'],
  data() {
    return {
      // 统计的专利数量
      copyrightCount: 0,
      // 全部产品
      productList: [],
      uploadLoading: false, // 上传动画
      env: process.env.VUE_APP_STATIC_API || "",
      // 文件列表
      fileList: [],
      // 加载动画
      loading: true,
      pickerOptions: {
        disabledDate(time) {
          // 禁止选择今天及今天之后的日期
          return time.getTime() > Date.now();
        }
      },
      // 活动日期
      activityDate: [],
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        transferorDate: "", // 转让日期
        series: [], // 所属系列
        authorizationDate: "", // 下证日期
        acquisitionMethod: "", // 取得方式（1=原始取得、2=转让）
        applicationDate: "", // 申请日期
        cooperativeAgency: "", // 合作机构
        correspondingDevice: [], // 对应设备
        highNewUsage: "", // 高新试用情况
        internationalClassification: "", // 国际分类（仅商标类型有效）
        inventor: [], // 发明人
        isAntecedentTrial: "", // 是否预审（0=否、1=是）
        name: "", // 知识产权名称
        patentType: "", // 专利类型（1=发明专利、2=实用新型专利、3=外观设计专利）
        registrant: "", // 注册人
        registrationDate: "", // 注册日期
        registrationNumber: "", // 登记号
        rightHolder: [], // 专利权人（专利、软著）
        serialNumber: "", // 序号
        status: "", // 状态（1=申请中、2=授权有效、3=授权失效、4=驳回）
        technologyPerson: "", // 技术对接人
        trademarkContent: "", // 商标内容（仅商标类型有效）
        trademarkPicture: "", // 商标图片存储路径
        transferorUnit: "", // 转让前单位
        type: 2, // 类型（1=专利、2=软著、3=商标）
        validityDate: "", // 有效期至
        createBy: "", // 创建人 *
        createTime: "", // 创建时间 *
        id: null, // id
        remark: "", // 备注
        updateBy: "", // 更新时间
        updateTime: "", // 更新人
      },
      // 表单的校验规则
      rules: {
        patentType: [
          {required: true, message: '请选择专利类型', trigger: 'change'}
        ],
        serialNumber: [
          {required: true, message: '请填写序号', trigger: 'blur'}
        ],
        // registrationNumber: [
        //   {required: true, message: '请填写专利号', trigger: 'blur'}
        // ],
        name: [
          {required: true, message: '请填写名称', trigger: 'blur'}
        ],
        acquisitionMethod: [
          {required: true, message: '请选择取得方式', trigger: 'change'}
        ],
        rightHolder: [
          {required: true, message: '请填写著作权人', trigger: 'change'}
        ],
        applicationDate: [
          {required: true, message: '请选择申请日期', trigger: 'change'}
        ],
        status: [
          {required: true, message: '请选择状态', trigger: 'change'}
        ],
        inventor: [
          {required: true, message: '请填写发明人', trigger: 'change'}
        ],
        correspondingDevice: [
          {required: true, message: '请填写对应设备', trigger: 'change'}
        ],
        highNewUsage: [
          {required: true, message: '请填写高新使用情况', trigger: 'blur'}
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        rightHolder: "",
        serialNumber: "", // 序号
        status: "", // 状态（1=申请中、2=授权有效、3=授权失效、4=驳回）
        acquisitionMethod: "", // 取得方式（1=原始取得、2=转让）
        patentType: "", // 专利类型（1=发明专利、2=实用新型专利、3=外观设计专利）
        type: 2, // 类型（1=专利、2=软著、3=商标）
        name: "",
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 是与否
      isOrNo: [
        {
          value: 0,
          label: "否"
        },
        {
          value: 1,
          label: "是"
        },
      ]
    }
  },
  watch: {
    activityDate: {
      handler(newV) {
        if (newV) {
          this.queryParams.startDate = newV[0] ?? ''
          this.queryParams.endDate = newV[1] ?? ''
        } else {
          this.queryParams.startDate = ''
          this.queryParams.endDate = ''
        }
      },
    },
    'form.isImportant': {
      handler(newV) {
        if (newV !== 1) {
          this.form.basis = null
        }
      }
    },
  },
  computed: {
    ...mapGetters([
      'device'
    ]),
  },
  created() {
    this.getList()
    this.getUserinfo()
    this.getAllProduct()
  },
  activated() {
    this.getList()
  },
  methods: {
    // 删除文件
    handleRemove(_, fileList) {
      this.fileList = fileList
    },
    getAllProduct() {
      getAllProductApi()
        .then((res) => {
          if (res.code === 200) {
            this.productList = res.rows
          }
        })
        .catch(() => {
        })
    },
    // 查看专利
    handleView2(row) {
      // console.log(row)
      window.open(this.env + row.certificate)
    },
    // 查看合同
    handleView(row) {
      this.$router.push({name: 'CopyrightDetail', query: {id: row.id}})
    },
    // 上传全部图片
    async uploadImg(fileList = [], cb = () => {
    }) {
      if (fileList.length <= 0) {
        cb && cb("")
        return false
      }

      const urlList = (fileList ?? []).filter(i => !i.raw).map(i => i.url)

      if (urlList && urlList[0]) return false

      if (fileList.length <= 0) {
        this.form.certificate = ""
        return false
      }

      const file = fileList[0]
      const formData = new FormData()
      formData.append('file', file.raw)
      const {fileName} = await uploadImgApi(formData)

      cb && cb(fileName)
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if (+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 选中图片
    handleChange(_, fileList) {
      const file = fileList[0] ?? null

      if (isFileOfType(file.name, ['.pdf'])) {
        this.fileList = fileList
      } else {
        this.$notify.error({
          title: '错误',
          message: '文件选择错误'
        });
        this.fileList = []
      }
    },
    // 获取数据
    async getList() {
      this.loading = true
      const { code, data } = await getDataListApi(this.queryParams)
      if (code === 200) {
        this.tableData = data?.list?.rows ?? []
        this.total = data?.list?.total ?? 0

        this.copyrightCount = data?.copyrightCount ?? 0
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.form = {
          ...row,
          correspondingDevice: row.correspondingDevice?.split(',')?.filter(i => i) ?? [],
          inventor: row.inventor?.split(',')?.filter(i => i) ?? [],
          rightHolder: row.rightHolder?.split(',')?.filter(i => i) ?? [],
          series: row.series?.split(',')?.filter(i => i) ?? [],
        }
        this.fileList = ((row.certificate ?? "").split(',') ?? []).filter(i => i).map(item => ({name: item, url: item}))
        this.dialogTitle = 2
      } else {
        this.fileList = []
          this.form = {...this.$options.data().form}
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      this.resetForm('formRef')
    },
    // 导出的回调
    async exportHandler() {
      this.download('saas/intellectualProperty/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `patents_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      // if (this.fileList.length <= 0) {
      //   this.$notify.error({
      //     title: '错误',
      //     message: '请上传软著证书'
      //   });
      //   return false
      // }
      const _this = this

      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            this.uploadLoading = true

            await this.uploadImg(this.fileList, (fileListStr) => {
              _this.form.certificate = fileListStr
            })
          } catch (error) {
            this.uploadLoading = false
          }

          this.uploadLoading = false

          if (this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        correspondingDevice: this.form.correspondingDevice.join(','),
        inventor: this.form.inventor.join(','),
        rightHolder: this.form.rightHolder.join(','),
        series: this.form.series.join(','),
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        correspondingDevice: this.form.correspondingDevice.join(','),
        inventor: this.form.inventor.join(','),
        rightHolder: this.form.rightHolder.join(','),
        series: this.form.series.join(','),
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.activityDate = []
      this.resetForm('queryFormRef')
    },
  },
}
</script>
<style scoped lang="scss">
.red-dot::before {
  content: '* ';
  color: red;
}

.text {
  color: red;
}
</style>
